package com.elbis.business.manager;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.elbis.business.entity.Gamer;
import com.elbis.business.entity.authentication.Authentication;
import com.elbis.util.HibernateUtil;

public class AuthenticationManager implements EntityManager<Authentication> {

	private static final Logger logger = Logger
			.getLogger(AuthenticationManager.class);

	@Override
	public Long save(Authentication auth) {
		Session session = HibernateUtil.getSession();

		Transaction trx = null;
		Long id = null;
		try {
			trx = session.beginTransaction();
			id = (Long) session.save(auth);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return id;
	}

	@Override
	public void delete(Authentication auth) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		try {
			trx = session.beginTransaction();
			session.delete(auth);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

	@Override
	public void update(Authentication auth) {
		Session session = HibernateUtil.getSession();
		Transaction trx = null;
		try {
			trx = session.beginTransaction();
			session.update(auth);
			trx.commit();
		} catch (HibernateException e) {
			if (trx != null) {
				trx.rollback();
			}
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Authentication> getFor(Gamer gamer) {
		Session session = HibernateUtil.getSession();
		List<Authentication> authenticaions = null;
		try {
			authenticaions = session.createCriteria(Authentication.class)
					.add(Restrictions.and(Restrictions.eq("gamer", gamer)))
					.list();
		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return authenticaions;
	}

}
